package auth

import (
	"common"
	"common/grpcx"
	"context"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc/metadata"
	"models/dal/model"
)

type (
	AuthObject struct {
		currentUser *model.FaUser
		ginCtx      *gin.Context
		grpcCtx     context.Context
	}
)

// NewAuthObjectByHttp 创建授权对象,基于http
func NewAuthObjectByHttp(ctx *gin.Context) *AuthObject {
	return &AuthObject{
		currentUser: nil,
		ginCtx:      ctx,
		grpcCtx:     nil,
	}
}

// NewAuthObjectByGrpc 创建授权对象,基于grpc
func NewAuthObjectByGrpc(ctx context.Context) *AuthObject {
	return &AuthObject{
		currentUser: nil,
		ginCtx:      nil,
		grpcCtx:     ctx,
	}
}

// GetGrpcAuthMetadata 获取grpc授权metadata
func (ao *AuthObject) GetGrpcAuthMetadata() metadata.MD {
	return grpcx.GetUserMetaData(ao.ginCtx)
}

// GetCurrentUser 获取当前授权对象
func (ao *AuthObject) GetCurrentUser() *model.FaUser {
	if ao.ginCtx != nil {
		ao.currentUser, _ = common.GetUserByHttp(ao.ginCtx)
	} else if ao.grpcCtx != nil {
		ao.currentUser, _ = common.GetUserByGrpc(ao.grpcCtx)
	}
	return ao.currentUser
}
